<?php

function connectDb() {
	try {
    	$db = mysql_connect(DB_SERVER . ':' . DB_PORT, DB_USER, DB_PASS);
		mysql_select_db(DB_BASE, $db);
		mysql_query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
		mysql_query("SET lc_time_names = 'fr_FR'");
    } catch(Exception $e) {
        die("Database not found");
    }
}

function fetch($sql) {
	$result = mysql_query($sql);
	if(!$result){
		die('requete invalide : '.mysql_error());
	}
	$results = array() ;
	while ($ligne = mysql_fetch_array($result)) {
		$results[] = $ligne;
	}
	mysql_free_result($result) ;
	return $results ;
}

function theme(){
	$theme = array();
	$theme["color1"] = "0"; //Assigning a variable with no value
	$theme["color2"] = "0"; //Assigning a variable with no value
	$theme["color3"] = "0"; //Assigning a variable with no value
	$nbTheme = rand(1, 3); //Getting random number 
	switch($nbTheme){
		case 1:
			$theme["color1"] = "yellow";
			$theme["color2"] = "dark_yellow";
			$theme["color3"] = "blue";
			break;
		case 2:
			$theme["color1"] = "red";
			$theme["color2"] = "dark_red";
			$theme["color3"] = "purple";
			break;
		case 3:
			$theme["color1"] = "orange";
			$theme["color2"] = "dark_orange";
			$theme["color3"] = "green";
			break;
		default: echo "Something going wrong!";
			break;
	}
	return $theme;
}

function chooseDate($user, $offset=0, $limit=5){
	$tabDates = array(
		'offset' => 0,
		'dates' => array()
	);
	$temp = $offset;
	$datetime = new DateTime();
	$limit += $offset;
	$pas = null;
		$newDate = new DateTime($user['date_begin']);
		$offset = $temp;
		if($user['daily']){	
			$pas = 	'+1 day';
		}
		elseif($user['weekly']){	
			$pas = 	'+7 day';	
		}
		elseif($user['monthly']){	
			$pas = 	'+1 month';	
		}
		elseif($user['yearly']){
			$pas = 	'+1 year';
		}
		else{
			$date = date_format($newDate, 'Y-m-d H:i:s');	
			array_push($tabDates['dates'], $date);
			$tabDates['offset'] = $offset;
			return $tabDates;
		}

		// Recalibrage par rapport à la date actuelle
		while($newDate < $datetime){
			date_modify($newDate, $pas);
		}

		// avance de n date selon le offset pour avoir le bon décalage.
		for($i=0; $i < $offset; $i++) { 
			date_modify($newDate, $pas);
		}

		if($newDate >= $datetime){
			while ($offset < $limit){
				// Rempli la première date déjà bonne avecla première actualisation de la date
				$date = date_format($newDate, 'Y-m-d H:i:s');
				if(!checkDates($date)){
					array_push($tabDates['dates'], $date);
				}
				else{
					$limit++;
				}				
				// incrémente d'un pas.
				date_modify($newDate, $pas);
				$offset++;
			}
		}
	$tabDates['offset'] = $offset;
	return $tabDates;
}
